#include "pipe_communicate.h"
/*
    管道通信库
*/

//管道初始化
int pipe_init(char *myfifo) {
    int fd;
    int res;

    // 判断是否存在命名管道文件
    if (access(myfifo, F_OK) != -1) {
        printf("%s 写入管道存在.\n", myfifo);
        // remove(myfifo);
        chmod(myfifo,0777);
    }else{
        //不存在
        res = mkfifo(myfifo, 0777);//问题：这里创建的并不是777权限，而是755
        if (res < 0) {
            printf("create fifo failure\n");
            exit(1);
        } else {
            chmod(myfifo,0777);
            printf(">>>Create pipe...OK!! \n");
        }
    }

    // 打开命名管道
    fd = open(myfifo, O_WRONLY );// | O_NONBLOCK
    if (fd < 0) {
        printf(">>>Failed to open pipe:%s,fd=%d \n",myfifo,fd);//
        pipe_cloes(fd,myfifo);
        exit(1);
    } else {
        printf(">>>Writing data to Pipe... fd=%d\n",fd);
    }

    return fd;
}

int pipe_open_read(char *myfifo){
    int fd;
    AAA:
        if (access(myfifo, F_OK) != -1) {
            printf("%s管道文件存在.\n", myfifo);
            fd = open(myfifo,O_RDONLY);
            return fd;
        }else{
            sleep(2);
            goto AAA;
        }
}

int pipe_receive(char r_l){

    char a[1280];
    memset(a,0,1280);

    switch (r_l)
    {
    case 'r':
        read(pipo_R_date_out_fd,a,1280);
        break;
    case 'l':
        read(pipo_L_date_out_fd,a,1280);
        break;
    default:
        return -1;
        break;
    }

    return 0;
}

//发送到管道中
int pipe_send(int *fd,unsigned char *data,int size){
	int ret=0;
	ret = write(fd, data, size);
	if(ret > 0){
		//printf(">>>write ok !!! ,size:%d \n\r",ret);
	}else{
		printf(">>>write error !!! ret=%d fd=%d \n\r",ret,fd);
	}
	return 0;
}
//关闭管道
int pipe_cloes(int fd,char *myfifo){
	close(fd);
    unlink(myfifo);
}

